'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');
class Login extends Controller {
  // 登录
  async login() {
    const { ctx } = this;
    const { user, password } = ctx.request.body;
    const results = await this.app.mysql.select('user', { // 搜索 post 表
      where: { user, password }, // WHERE 条件
    });
    if (results.length) {
      const token = jwt.sign({ user, password }, 'zj', { expiresIn: '1h' });
      ctx.body = {
        code: 200,
        data: results,
        token,
        msg: '登录成功',
        img: results[0].img,
        auth: results[0].auth,
      };
    } else {
      ctx.body = {
        code: 404,
        msg: '账号密码错误',
      };
    }

  }

  // 注册
  async signIn() {
    const { ctx } = this;
    const { user, password } = ctx.request.body;
    const results = await this.app.mysql.select('user', { // 搜索 post 表
      where: { user }, // WHERE 条件
    });
    if (results.length) {
      ctx.body = {
        code: 402,
        msg: '账号已存在，请直接登录',
      };
    } else {
      const result = await this.app.mysql.insert('user', { user, password });
      if (result.affectedRows === 1) {
        ctx.body = {
          code: 200,
          msg: '注册成功，请重新登录',
        };
      } else {
        ctx.body = {
          code: 402,
          msg: '错误，注册失败',
        };
      }
    }
  }
}

module.exports = Login;
